import csv
import os
import threading
import tkinter as tk
from datetime import datetime
from tkinter import filedialog, messagebox

import xlwt


def open_file():
    file_path = filedialog.askopenfilename()
    print(file_path, type(file_path))
    if file_path:
        with open(file_path, 'r') as file:
            reader = csv.reader(file)
            # start_index = 35
            # finish_index = 13686
            start_index = 27
            finish_index = 2504
            data_list_for_dic = []
            y_coordinate = []
            x_coordinate = []
            data_dict = {}
            count = 0
            for i, row in enumerate(reader):
                if i < start_index:
                    continue
                if i > finish_index:
                    break
                y_coordinate.append(int(row[7]))
                x_coordinate.append(int(row[6]))
                count += 1
                # dataList.append(row[3] + row[4])
                # dataList.append(row[2])
                data_list_for_dic.append(row[4:8])
            for i in range(len(data_list_for_dic)):
                data_dict[data_list_for_dic[i][2] + "+" + data_list_for_dic[i][3]] = data_list_for_dic[i][0]

            sheet_name_xls = "sheet"
            write_excel_xls(sheet_name_xls, y_coordinate, x_coordinate, data_dict)


def write_excel_xls(sheet_name, y_coordinate, x_coordinate, data_dict):
    # threading.Thread(target=decoration_thread)
    print("xls格式表格开始写入！")
    # 获取当前时间
    start_time = datetime.now()
    workbook = xlwt.Workbook()  # 新建一个工作簿
    # print(data_dict)
    sheet = workbook.add_sheet(sheet_name, cell_overwrite_ok=True)  # 新建一个工作表

    for i, x in enumerate(x_coordinate):
        result_label.config(text=f"xls格式表格正在写入{i + 1}/{len(x_coordinate)}")
        window.update_idletasks()
        for y in y_coordinate:
            sheet.write(y, x, data_dict.get(str(x) + "+" + str(y), None))
    formatted_time = start_time.strftime("%Y%m%d-%H%M%S")
    print(formatted_time)
    out_directory = "D:/CP"
    if os.path.isdir(out_directory):
        print("目录存在")
    else:
        print("目录不存在,创建ing")
        os.makedirs(out_directory)
    out_all_path = f"D:/CP/huanxuan_CP921_out{formatted_time}.xls"
    workbook.save(out_all_path)  # 保存工作簿
    print("xls格式表格写入数据成功！")
    # 计算时间差
    end_time = datetime.now()
    time_difference = end_time - start_time
    print(f"总共耗时 {time_difference}")
    result_label.config(text="xls格式表格写入数据成功")
    messagebox.showinfo("提示", f"生成Excel成功,路径{out_all_path}")
    print(out_all_path)

# 创建窗口对象
window = tk.Tk()
window.title("huanxuanCP921")
window.geometry("400x300")
# 创建按钮组件
button = tk.Button(window, text="打开文件", command=open_file)
# button.place(x=50, y=100)
# button.grid(row=1, column=0, padx=10, pady=10)
button.config(height=2, width=25)
button.pack()

result_label = tk.Label(window, text="")
result_label.pack()

# 运行主循环
window.mainloop()
